package com.example.app;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.app.ui.main.WpsFileFragment;
import com.getcapacitor.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import cn.wps.moffice.demo.client.MOfficeClientService;
import cn.wps.moffice.demo.fileManager.OpenFile;
import cn.wps.moffice.demo.util.Define;
import cn.wps.moffice.demo.util.SettingPreference;
import cn.wps.moffice.demo.util.Util;
import cn.wps.moffice.service.OfficeService;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class WpsFileActivity extends AppCompatActivity {

    // WPS用的参数对象
    SettingPreference settingPreference;

    // 外面传过来的参数
    protected Map<String, String> paramMap = new HashMap<String, String>();

    private String strFileId;
    private String strFileName;
    private String strFolder;
    private String strFilePath;

    protected String getParam(String strKey)
    {
        if (this.paramMap.containsKey(strKey))
        {
            return this.paramMap.get(strKey);
        }

        return "";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置layout
//        setContentView(R.layout.wps_file_activity);
//        if (savedInstanceState == null) {
//            getSupportFragmentManager().beginTransaction()
//                    .replace(R.id.container, WpsFileFragment.newInstance())
//                    .commitNow();
//        }

        // 解析Intent传过来的参数，并存入paramMap
        if (getIntent() != null && getIntent().getExtras() != null)
        {
            Bundle bundle = getIntent().getExtras();
            for (String strKey : bundle.keySet())
            {
                paramMap.put(strKey, bundle.getString(strKey));
            }
        }

        //启动client service
        Intent intent = new Intent( this, MOfficeClientService.class);
        startService(intent);

        // 设置
        settingPreference = new SettingPreference(this);
        settingPreference.setSettingParam(Define.KEY, getPackageName());
        settingPreference.setSettingParam("agentClassName","cn.wps.moffice.agent.OfficeServiceAgentGXJCY");
        settingPreference.setSettingParam(Define.ENCRYPT_FILE, false);
        settingPreference.setSettingParam(Define.WPS_OPEN_MODE, Define.WPS_OPEN_AIDL);
        settingPreference.setSettingParam(Define.USER_NAME, "TODO用户名");

        // 设置只读还是
        String readOnly = this.getParam("readOnly");
        if("true".equals(readOnly))
            settingPreference.setSettingParam(Define.OPEN_MODE,  Define.READ_ONLY);
        else
            settingPreference.setSettingParam(Define.OPEN_MODE,  Define.OPEN_MODE);

        settingPreference.setSettingParam(Define.AT_MULTIDOCCHANGE, false);
        settingPreference.setSettingParam(Define.SEND_SAVE_BROAD, true);
        settingPreference.setSettingParam(Define.SEND_CLOSE_BROAD, true);
        settingPreference.setSettingParam(Define.BACK_KEY_DOWN, true);
        settingPreference.setSettingParam(Define.HOME_KEY_DOWN, true);

        settingPreference.setSettingParam(Define.AT_SAVEAS,false);//禁止另存
        settingPreference.setSettingParam(Define.AT_SHARE,false);//禁止分享
        settingPreference.setSettingParam(Define.AT_PRINT,false);//禁止打印
        settingPreference.setSettingParam(Define.AT_SHARE_PLAY,false);//禁止共享播放
        settingPreference.setSettingParam("AT_EXPORT_AS_PDF",false);//禁止输出PDF

        strFileId = this.getParam("fileid");
        strFileName=this.getParam("filename");
        strFolder = getApplicationContext().getFilesDir().getAbsolutePath();
        settingPreference.setSettingParam("fileid", strFileId);
        settingPreference.setSettingParam("filepath", strFolder);
        settingPreference.setSettingParam("filename", strFileName);
        settingPreference.setSettingParam("uploadUrl", getParam("uploadUrl"));

        downloadFile(strFileName);
        bindOfficeService();

//        System.out.println("WWWWW:"+Environment.getExternalStorageDirectory().getAbsolutePath());
//
//        File currentParent = new File(Environment.getExternalStorageDirectory().getAbsolutePath());					// 记录当前的父文件夹
//        File[] currentFiles = currentParent.listFiles();
//        for (File x : currentFiles) {
//            System.out.println("WWWWW:"+x.getAbsolutePath());
//        }

//        File file = new File(strFolder);
//
//        if (file.exists())
//        {
//            file.delete();
//        }

    }

//    //读写权限
//    private static String[] PERMISSIONS_STORAGE = {
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE};
//    //请求状态码
//    private static int REQUEST_PERMISSION_CODE = 1;
//
//    //获取权限
//    private void getPermission(){
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
//            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
//            }
//        }
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == REQUEST_PERMISSION_CODE) {
//            for (int i = 0; i < permissions.length; i++) {
//                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
//            }
//        }
//    }

    private OfficeService mService;

    private ServiceConnection connection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            // 给activity绑定office服务
            mService = OfficeService.Stub.asInterface(service);

            WpsFileActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    File file=new File(strFilePath);
                    if (Util.IsWPSFile(file)) {
                        OpenFile openFile = new OpenFile(mService, getApplicationContext());
                        //如果是WPS支持打开的文件，则打开
                        openFile.openDocument(strFilePath);
                    }

                }
            });


        }

        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            mService = null;
        }
    };


    /**
     *  绑定Office服务
     * @return
     */
    private boolean bindOfficeService() {
        // 先启动moffice进程
        final Intent startAppIntent = new Intent();
        startAppIntent.setClassName("com.kingsoft.moffice_pro", "cn.wps.moffice.second_dev.StartAppActivity");
        startAppIntent.setAction("cn.wps.moffice.second_dev.StartApp");
        startAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startAppIntent);

        // 绑定office服务
        final Intent intent = new Intent(Define.OFFICE_SERVICE_ACTION);
        intent.setPackage("com.kingsoft.moffice_pro");
        intent.putExtra("DisplayView", true);

        // 每隔半秒尝试一次绑定服务，尝试10次
        boolean bindOk = false;
        for (int i = 0 ; i < 10 ; ++i)
        {
            bindOk = bindService(intent, connection, Service.BIND_AUTO_CREATE);

            if (bindOk)
                break;
            else
            {
                try
                {
                    Thread.sleep(500);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                    break;
                }
            }

        }

        // 服务绑定失败时
        if (!bindOk)
        {
            // bind failed, maybe wps office is not installd yet.
            Util.showToast(getApplicationContext(), "服务绑定失败！");
            unbindService(connection);
            this.finish();
            return false;
        }
        this.finish();
        return true;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }


    /**
     * 下载文件
     * @param filename
     * @return
     */
    public File downloadFile(String filename)
    {
        OkHttpClient okhttp = new OkHttpClient();
        if(filename == null || filename.isEmpty())
            return null;

        FutureTask<File> task = new FutureTask<>(()->
        {
            Response response = okhttp.newCall(
                    new Request.Builder().url(getParam("downloadUrl")).build()
            ).execute();
            ResponseBody responseBody = response.body();
            if(responseBody != null)
            {
                if(getExternalFilesDir(null) != null)
                {
                    strFilePath = getExternalFilesDir(null).toString() + "/" + filename;
                    File file = new File(strFilePath);
                    // 删除本地同名的文件，否则内容不会变
                    if(file.exists()){
                        file.delete();
                    }
                    try (
                            InputStream inputStream = responseBody.byteStream();
                            FileOutputStream outputStream = new FileOutputStream(file)
                    )
                    {
                        byte[] b = new byte[1024];
                        int n;
                        if((n = inputStream.read(b)) != -1)
                        {
                            outputStream.write(b,0,n);
                            while ((n = inputStream.read(b)) != -1)
                                outputStream.write(b, 0, n);
                            return file;
                        }
                        else
                        {
                            file.delete();
                            return null;
                        }
                    }finally {
                    }
                }
            }
            return null;
        });
        try
        {
            new Thread(task).start();
            return task.get();
        }
        catch (InterruptedException | ExecutionException e)
        {
            e.printStackTrace();
            return null;
        }
    }



}